import Vue from 'vue'
import Vuex from 'vuex'
import { setTokenStorage, removeTokenStorage, getTokenStorage } from '@/utils/storage'
import { getUserInfo } from '@/api/user'
import { getChannels, getAllChannels } from '@/api/channel'
Vue.use(Vuex)

export default new Vuex.Store({
  // 严格模式
  strict: process.env.NODE_ENV === 'development',
  state: {
    // 从storage中获取
    token: getTokenStorage() || {},
    user: {},
    // 存放我的频道
    channelList: [],
    // 存放所有的频道
    allChannelList: []
  },
  mutations: {
    setToken (state, token) {
      // vuex存储了token
      state.token = token
      // localStorage中存储token
      setTokenStorage(token)
    },
    removeToken (state) {
      // 删除vuex中token
      state.token = {}
      // 删除storage中的token
      removeTokenStorage()
      // 删除vuex中user
      state.user = {}
    },
    setUser (state, user) {
      state.user = user
    },
    setChannels (state, channels) {
      state.channelList = channels
    },
    setAllChannelList (state, channels) {
      state.allChannelList = channels
    },
    // 添加频道
    addChannel (state, channel) {
      state.channelList.push(channel)
    },
    delChannel (state, channel) {
      state.channelList = state.channelList.filter(item => item.id !== channel.id)
    }
  },
  actions: {
    async getUser (context) {
      // 发送请求-获取个人信息
      const res = await getUserInfo()
      console.log(res.data)
      context.commit('setUser', res.data)
    },
    async getChannelList ({ commit }) {
      const res = await getChannels()
      // console.log(res.data.channels)
      commit('setChannels', res.data.channels)
    },
    async getAllChannelList ({ commit }) {
      const res = await getAllChannels()
      commit('setAllChannelList', res.data.channels)
    }
  },
  // vuex的计算属性
  getters: {
    // 可选频道
    // optionalChannelList (state) {
    //   // 可选频道 = 全部频道 - 我的频道
    //   return state.allChannelList.filter(item => {
    //     // item在channelList中是否存在
    //     var idx = state.channelList.findIndex(v => v.id === item.id)
    //     if (idx === -1) {
    //       return true
    //     } else {
    //       return false
    //     }
    //   })
    // },
    optionalChannelList (state) {
      // 可选频道 = 全部频道 - 我的频道
      // return state.allChannelList.filter(item => state.channelList.findIndex(v => v.id === item.id) === -1)
      return state.allChannelList.filter(item => !state.channelList.some(v => v.id === item.id))
    }
  }
})
